import { createClient, SupabaseClient } from '@supabase/supabase-js';
import winston from 'winston';
import crypto from 'crypto';
import { v4 as uuidv4 } from 'uuid';

export interface ComplianceSettings {
  canSpam: {
    enabled: boolean;
    senderName: string;
    senderAddress: {
      street: string;
      city: string;
      state: string;
      zipCode: string;
      country: string;
    };
    optOutMethods: string[];
    honorOptOutTimeframe: number; // Hours
  };
  gdpr: {
    enabled: boolean;
    dataProcessingBasis: string;
    retentionPeriod: number; // Days
    dpoContact: string;
    privacyPolicyUrl: string;
    cookiePolicyUrl: string;
  };
  doubleOptIn: {
    enabled: boolean;
    confirmationTimeframe: number; // Hours
    confirmationSubject: string;
    requireConfirmation: boolean;
  };
  deliverySettings: {
    maxDailyEmails: number;
    maxWeeklyEmails: number;
    bounceThreshold: number; // Percentage
    spamComplaintThreshold: number; // Percentage
    rateLimitWindow: number; // Minutes
    rateLimitMax: number; // Emails per window
  };
}

export interface ConsentRecord {
  userId: string;
  email: string;
  consentType: 'opt_in' | 'double_opt_in' | 'legitimate_interest' | 'contract';
  consentSource: 'registration' | 'subscription_form' | 'api' | 'import' | 'manual';
  consentData: {
    ipAddress?: string;
    userAgent?: string;
    timestamp: Date;
    formData?: Record<string, any>;
    sourceUrl?: string;
    campaign?: string;
  };
  consentStatus: 'pending' | 'confirmed' | 'withdrawn' | 'expired';
  confirmationToken?: string;
  confirmationSentAt?: Date;
  confirmedAt?: Date;
  withdrawnAt?: Date;
  gdprCompliant: boolean;
  canSpamCompliant: boolean;
}

export interface DataProcessingRecord {
  userId: string;
  processingType: 'email_marketing' | 'analytics' | 'personalization' | 'research';
  legalBasis: 'consent' | 'legitimate_interest' | 'contract' | 'legal_obligation';
  purpose: string;
  dataCategories: string[];
  retentionPeriod: number; // Days
  thirdPartySharing: boolean;
  thirdParties?: string[];
  createdAt: Date;
  updatedAt: Date;
}

export interface ComplianceReport {
  period: {
    start: Date;
    end: Date;
  };
  metrics: {
    totalEmails: number;
    bounceRate: number;
    spamComplaintRate: number;
    unsubscribeRate: number;
    gdprRequests: number;
    canSpamViolations: number;
    doubleOptInRate: number;
  };
  violations: Array<{
    type: string;
    severity: 'low' | 'medium' | 'high' | 'critical';
    description: string;
    count: number;
    remediation: string;
  }>;
  recommendations: string[];
}

export class EmailComplianceService {
  private supabase: SupabaseClient;
  private logger: winston.Logger;
  private settings: ComplianceSettings;

  constructor(
    supabaseUrl: string,
    supabaseKey: string,
    logger: winston.Logger,
    settings?: Partial<ComplianceSettings>
  ) {
    this.supabase = createClient(supabaseUrl, supabaseKey);
    this.logger = logger;

    this.settings = {
      canSpam: {
        enabled: true,
        senderName: 'ArXiv Research Hub',
        senderAddress: {
          street: '123 Research Ave',
          city: 'San Francisco',
          state: 'CA',
          zipCode: '94102',
          country: 'USA'
        },
        optOutMethods: ['email_link', 'reply_email', 'web_form'],
        honorOptOutTimeframe: 10 // 10 business days as per CAN-SPAM
      },
      gdpr: {
        enabled: true,
        dataProcessingBasis: 'consent',
        retentionPeriod: 1095, // 3 years
        dpoContact: 'dpo@arxiv-hub.com',
        privacyPolicyUrl: 'https://arxiv-hub.com/privacy',
        cookiePolicyUrl: 'https://arxiv-hub.com/cookies'
      },
      doubleOptIn: {
        enabled: true,
        confirmationTimeframe: 24, // 24 hours
        confirmationSubject: 'Please confirm your subscription',
        requireConfirmation: true
      },
      deliverySettings: {
        maxDailyEmails: 50000,
        maxWeeklyEmails: 300000,
        bounceThreshold: 5, // 5%
        spamComplaintThreshold: 0.1, // 0.1%
        rateLimitWindow: 60, // 1 hour
        rateLimitMax: 10000 // Max emails per hour
      },
      ...settings
    };
  }

  /**
   * Record user consent for email communications
   */
  async recordConsent(
    userId: string,
    email: string,
    consentData: {
      source: string;
      ipAddress?: string;
      userAgent?: string;
      formData?: Record<string, any>;
      sourceUrl?: string;
      campaign?: string;
    }
  ): Promise<{ success: boolean; requiresDoubleOptIn: boolean; confirmationToken?: string }> {
    try {
      const consentId = uuidv4();
      let confirmationToken: string | undefined;
      let consentStatus: 'pending' | 'confirmed' = 'confirmed';

      // Generate confirmation token if double opt-in is required
      if (this.settings.doubleOptIn.enabled && this.settings.doubleOptIn.requireConfirmation) {
        confirmationToken = this.generateConfirmationToken(userId, email);
        consentStatus = 'pending';
      }

      // Create consent record
      const consentRecord: ConsentRecord = {
        userId,
        email,
        consentType: this.settings.doubleOptIn.enabled ? 'double_opt_in' : 'opt_in',
        consentSource: consentData.source as any,
        consentData: {
          ipAddress: consentData.ipAddress,
          userAgent: consentData.userAgent,
          timestamp: new Date(),
          formData: consentData.formData,
          sourceUrl: consentData.sourceUrl,
          campaign: consentData.campaign
        },
        consentStatus,
        confirmationToken,
        confirmationSentAt: confirmationToken ? new Date() : undefined,
        gdprCompliant: this.settings.gdpr.enabled,
        canSpamCompliant: this.settings.canSpam.enabled
      };

      // Store consent record
      const { error } = await this.supabase
        .from('email_consent_records')
        .insert({
          consent_id: consentId,
          user_id: userId,
          email,
          consent_type: consentRecord.consentType,
          consent_source: consentRecord.consentSource,
          consent_data: consentRecord.consentData,
          consent_status: consentRecord.consentStatus,
          confirmation_token: confirmationToken,
          confirmation_sent_at: consentRecord.confirmationSentAt?.toISOString(),
          gdpr_compliant: consentRecord.gdprCompliant,
          can_spam_compliant: consentRecord.canSpamCompliant,
          created_at: new Date().toISOString()
        });

      if (error) {
        throw error;
      }

      // Record data processing purposes
      await this.recordDataProcessing(userId, {
        processingType: 'email_marketing',
        legalBasis: 'consent',
        purpose: 'Send personalized research paper recommendations and updates',
        dataCategories: ['email_address', 'research_preferences', 'interaction_history'],
        retentionPeriod: this.settings.gdpr.retentionPeriod,
        thirdPartySharing: false
      });

      this.logger.info(`Consent recorded for user ${userId}: ${consentStatus}`);

      return {
        success: true,
        requiresDoubleOptIn: consentStatus === 'pending',
        confirmationToken
      };

    } catch (error) {
      this.logger.error(`Failed to record consent for user ${userId}:`, error);
      return { success: false, requiresDoubleOptIn: false };
    }
  }

  /**
   * Process double opt-in confirmation
   */
  async confirmOptIn(token: string): Promise<{
    success: boolean;
    userId?: string;
    email?: string;
    error?: string;
  }> {
    try {
      // Verify and decode token
      const tokenData = this.verifyConfirmationToken(token);
      if (!tokenData) {
        return { success: false, error: 'Invalid or expired confirmation token' };
      }

      // Find pending consent record
      const { data: consentRecord, error: fetchError } = await this.supabase
        .from('email_consent_records')
        .select('*')
        .eq('confirmation_token', token)
        .eq('consent_status', 'pending')
        .single();

      if (fetchError || !consentRecord) {
        return { success: false, error: 'Consent record not found or already confirmed' };
      }

      // Check if confirmation is within timeframe
      const confirmationSentAt = new Date(consentRecord.confirmation_sent_at);
      const now = new Date();
      const hoursElapsed = (now.getTime() - confirmationSentAt.getTime()) / (1000 * 60 * 60);

      if (hoursElapsed > this.settings.doubleOptIn.confirmationTimeframe) {
        // Mark as expired
        await this.supabase
          .from('email_consent_records')
          .update({ 
            consent_status: 'expired',
            updated_at: new Date().toISOString()
          })
          .eq('confirmation_token', token);

        return { success: false, error: 'Confirmation token has expired' };
      }

      // Confirm the opt-in
      const { error: updateError } = await this.supabase
        .from('email_consent_records')
        .update({
          consent_status: 'confirmed',
          confirmed_at: new Date().toISOString(),
          updated_at: new Date().toISOString()
        })
        .eq('confirmation_token', token);

      if (updateError) {
        throw updateError;
      }

      // Enable email notifications for the user
      await this.enableEmailNotifications(consentRecord.user_id);

      this.logger.info(`Double opt-in confirmed for user ${consentRecord.user_id}`);

      return {
        success: true,
        userId: consentRecord.user_id,
        email: consentRecord.email
      };

    } catch (error) {
      this.logger.error(`Failed to confirm opt-in for token ${token}:`, error);
      return { success: false, error: 'Failed to process confirmation' };
    }
  }

  /**
   * Process opt-out/unsubscribe request
   */
  async processOptOut(
    userId: string,
    method: 'email_link' | 'reply_email' | 'web_form' | 'api',
    metadata?: Record<string, any>
  ): Promise<{ success: boolean; error?: string }> {
    try {
      // Update consent status to withdrawn
      const { error: consentError } = await this.supabase
        .from('email_consent_records')
        .update({
          consent_status: 'withdrawn',
          withdrawn_at: new Date().toISOString(),
          withdrawal_method: method,
          withdrawal_metadata: metadata,
          updated_at: new Date().toISOString()
        })
        .eq('user_id', userId);

      if (consentError) {
        throw consentError;
      }

      // Disable email notifications immediately (CAN-SPAM compliance)
      await this.disableEmailNotifications(userId);

      // Record opt-out event for compliance tracking
      await this.supabase
        .from('compliance_events')
        .insert({
          user_id: userId,
          event_type: 'opt_out',
          event_method: method,
          event_metadata: metadata,
          compliance_requirement: 'CAN_SPAM',
          processing_time: new Date().toISOString(),
          created_at: new Date().toISOString()
        });

      this.logger.info(`Opt-out processed for user ${userId} via ${method}`);
      return { success: true };

    } catch (error) {
      this.logger.error(`Failed to process opt-out for user ${userId}:`, error);
      return { success: false, error: error instanceof Error ? error.message : 'Unknown error' };
    }
  }

  /**
   * Handle GDPR data subject requests
   */
  async handleGDPRRequest(
    userId: string,
    requestType: 'access' | 'rectification' | 'erasure' | 'portability' | 'restriction',
    requesterEmail: string,
    requestDetails?: Record<string, any>
  ): Promise<{ success: boolean; requestId?: string; error?: string }> {
    try {
      const requestId = uuidv4();

      // Verify the requester is the data subject
      const { data: user } = await this.supabase
        .from('users')
        .select('email')
        .eq('user_id', userId)
        .single();

      if (!user || user.email !== requesterEmail) {
        return { success: false, error: 'Email address does not match user record' };
      }

      // Create GDPR request record
      const { error } = await this.supabase
        .from('gdpr_requests')
        .insert({
          request_id: requestId,
          user_id: userId,
          requester_email: requesterEmail,
          request_type: requestType,
          request_details: requestDetails,
          request_status: 'pending',
          submitted_at: new Date().toISOString(),
          response_due_date: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString() // 30 days
        });

      if (error) {
        throw error;
      }

      // Process certain requests automatically
      if (requestType === 'erasure') {
        await this.processDataErasure(userId, requestId);
      } else if (requestType === 'access') {
        await this.generateDataExport(userId, requestId);
      }

      // Log compliance event
      await this.supabase
        .from('compliance_events')
        .insert({
          user_id: userId,
          event_type: 'gdpr_request',
          event_method: requestType,
          event_metadata: { requestId, requestDetails },
          compliance_requirement: 'GDPR',
          processing_time: new Date().toISOString(),
          created_at: new Date().toISOString()
        });

      this.logger.info(`GDPR ${requestType} request submitted for user ${userId}: ${requestId}`);

      return { success: true, requestId };

    } catch (error) {
      this.logger.error(`Failed to handle GDPR request for user ${userId}:`, error);
      return { success: false, error: error instanceof Error ? error.message : 'Unknown error' };
    }
  }

  /**
   * Check if email sending is compliant for user
   */
  async checkSendingCompliance(userId: string): Promise<{
    canSend: boolean;
    reasons: string[];
    violations: Array<{ type: string; severity: string; description: string }>;
  }> {
    const reasons: string[] = [];
    const violations: Array<{ type: string; severity: string; description: string }> = [];

    try {
      // Check consent status
      const { data: consent } = await this.supabase
        .from('email_consent_records')
        .select('*')
        .eq('user_id', userId)
        .eq('consent_status', 'confirmed')
        .order('created_at', { ascending: false })
        .limit(1)
        .single();

      if (!consent) {
        reasons.push('No valid consent record');
        violations.push({
          type: 'consent',
          severity: 'high',
          description: 'User has not provided valid consent for email communications'
        });
        return { canSend: false, reasons, violations };
      }

      // Check if user has opted out
      if (consent.consent_status === 'withdrawn') {
        reasons.push('User has opted out');
        violations.push({
          type: 'opt_out',
          severity: 'critical',
          description: 'User has withdrawn consent - sending would violate CAN-SPAM and GDPR'
        });
        return { canSend: false, reasons, violations };
      }

      // Check rate limits
      const rateLimitCheck = await this.checkRateLimits(userId);
      if (!rateLimitCheck.withinLimits) {
        reasons.push('Rate limit exceeded');
        violations.push({
          type: 'rate_limit',
          severity: 'medium',
          description: `User has exceeded email rate limits: ${rateLimitCheck.reason}`
        });
        return { canSend: false, reasons, violations };
      }

      // Check bounce and complaint rates
      const reputationCheck = await this.checkSenderReputation(userId);
      if (!reputationCheck.acceptable) {
        reasons.push('Poor sender reputation');
        violations.push({
          type: 'reputation',
          severity: 'high',
          description: `High bounce or complaint rate: ${reputationCheck.reason}`
        });
        return { canSend: false, reasons, violations };
      }

      // Check if user is in suppression list
      const { data: suppressed } = await this.supabase
        .from('email_suppression_list')
        .select('reason, added_at')
        .eq('user_id', userId)
        .eq('is_active', true)
        .single();

      if (suppressed) {
        reasons.push(`User is suppressed: ${suppressed.reason}`);
        violations.push({
          type: 'suppression',
          severity: 'high',
          description: `User is on suppression list: ${suppressed.reason}`
        });
        return { canSend: false, reasons, violations };
      }

      return { canSend: true, reasons: [], violations: [] };

    } catch (error) {
      this.logger.error(`Failed to check sending compliance for user ${userId}:`, error);
      return {
        canSend: false,
        reasons: ['Compliance check failed'],
        violations: [{
          type: 'system_error',
          severity: 'critical',
          description: 'Unable to verify compliance status'
        }]
      };
    }
  }

  /**
   * Add required compliance headers and footers to email
   */
  addComplianceContent(
    html: string,
    userId: string,
    unsubscribeUrl: string
  ): string {
    let compliantHtml = html;

    // Add CAN-SPAM compliant unsubscribe footer
    if (this.settings.canSpam.enabled) {
      const footer = this.generateCanSpamFooter(unsubscribeUrl);
      compliantHtml = compliantHtml.replace('</body>', `${footer}\n</body>`);
    }

    // Add GDPR privacy notice if required
    if (this.settings.gdpr.enabled) {
      const gdprNotice = this.generateGDPRNotice();
      compliantHtml = compliantHtml.replace('</body>', `${gdprNotice}\n</body>`);
    }

    return compliantHtml;
  }

  /**
   * Generate compliance report
   */
  async generateComplianceReport(startDate: Date, endDate: Date): Promise<ComplianceReport> {
    try {
      // Get email metrics
      const { data: deliveryLogs } = await this.supabase
        .from('email_delivery_logs')
        .select('delivery_status, bounce_reason')
        .gte('delivery_timestamp', startDate.toISOString())
        .lte('delivery_timestamp', endDate.toISOString());

      const totalEmails = deliveryLogs?.length || 0;
      const bounced = deliveryLogs?.filter(log => log.delivery_status === 'bounced').length || 0;
      const complaints = deliveryLogs?.filter(log => 
        log.delivery_status === 'spam' || 
        log.bounce_reason?.toLowerCase().includes('spam')
      ).length || 0;

      // Get unsubscribe data
      const { data: optOuts } = await this.supabase
        .from('email_consent_records')
        .select('withdrawn_at')
        .eq('consent_status', 'withdrawn')
        .gte('withdrawn_at', startDate.toISOString())
        .lte('withdrawn_at', endDate.toISOString());

      // Get GDPR requests
      const { data: gdprRequests } = await this.supabase
        .from('gdpr_requests')
        .select('request_type')
        .gte('submitted_at', startDate.toISOString())
        .lte('submitted_at', endDate.toISOString());

      // Get double opt-in stats
      const { data: confirmations } = await this.supabase
        .from('email_consent_records')
        .select('consent_status, confirmed_at')
        .gte('created_at', startDate.toISOString())
        .lte('created_at', endDate.toISOString());

      const pendingConfirmations = confirmations?.filter(c => c.consent_status === 'pending').length || 0;
      const confirmedOptIns = confirmations?.filter(c => c.consent_status === 'confirmed').length || 0;

      const bounceRate = totalEmails > 0 ? (bounced / totalEmails) * 100 : 0;
      const spamComplaintRate = totalEmails > 0 ? (complaints / totalEmails) * 100 : 0;
      const unsubscribeRate = totalEmails > 0 ? ((optOuts?.length || 0) / totalEmails) * 100 : 0;
      const doubleOptInRate = (pendingConfirmations + confirmedOptIns) > 0 ? 
        (confirmedOptIns / (pendingConfirmations + confirmedOptIns)) * 100 : 0;

      // Identify violations
      const violations = [];
      const recommendations = [];

      if (bounceRate > this.settings.deliverySettings.bounceThreshold) {
        violations.push({
          type: 'high_bounce_rate',
          severity: 'high' as const,
          description: `Bounce rate (${bounceRate.toFixed(2)}%) exceeds threshold (${this.settings.deliverySettings.bounceThreshold}%)`,
          count: bounced,
          remediation: 'Review list hygiene practices and implement better email validation'
        });
        recommendations.push('Implement stricter email validation and list cleaning procedures');
      }

      if (spamComplaintRate > this.settings.deliverySettings.spamComplaintThreshold) {
        violations.push({
          type: 'high_spam_rate',
          severity: 'critical' as const,
          description: `Spam complaint rate (${spamComplaintRate.toFixed(2)}%) exceeds threshold (${this.settings.deliverySettings.spamComplaintThreshold}%)`,
          count: complaints,
          remediation: 'Review email content and sending practices immediately'
        });
        recommendations.push('Audit email content for spam triggers and review sending frequency');
      }

      if (doubleOptInRate < 70) {
        violations.push({
          type: 'low_confirmation_rate',
          severity: 'medium' as const,
          description: `Double opt-in confirmation rate (${doubleOptInRate.toFixed(2)}%) is below recommended 70%`,
          count: pendingConfirmations,
          remediation: 'Optimize confirmation email content and process'
        });
        recommendations.push('Improve double opt-in email design and follow-up sequence');
      }

      return {
        period: { start: startDate, end: endDate },
        metrics: {
          totalEmails,
          bounceRate,
          spamComplaintRate,
          unsubscribeRate,
          gdprRequests: gdprRequests?.length || 0,
          canSpamViolations: violations.filter(v => v.type.includes('spam')).length,
          doubleOptInRate
        },
        violations,
        recommendations
      };

    } catch (error) {
      this.logger.error('Failed to generate compliance report:', error);
      throw error;
    }
  }

  /**
   * Private helper methods
   */
  private generateConfirmationToken(userId: string, email: string): string {
    const payload = JSON.stringify({
      userId,
      email,
      timestamp: Date.now(),
      expires: Date.now() + (this.settings.doubleOptIn.confirmationTimeframe * 60 * 60 * 1000)
    });

    const token = crypto
      .createHmac('sha256', process.env.CONFIRMATION_SECRET || 'default-secret')
      .update(payload)
      .digest('base64url');

    return `${Buffer.from(payload).toString('base64url')}.${token}`;
  }

  private verifyConfirmationToken(token: string): { userId: string; email: string } | null {
    try {
      const [payloadB64, signature] = token.split('.');
      const payload = JSON.parse(Buffer.from(payloadB64, 'base64url').toString());

      // Verify signature
      const expectedSignature = crypto
        .createHmac('sha256', process.env.CONFIRMATION_SECRET || 'default-secret')
        .update(JSON.stringify(payload))
        .digest('base64url');

      if (signature !== expectedSignature) {
        return null;
      }

      // Check expiration
      if (Date.now() > payload.expires) {
        return null;
      }

      return { userId: payload.userId, email: payload.email };
    } catch {
      return null;
    }
  }

  private async enableEmailNotifications(userId: string): Promise<void> {
    await this.supabase
      .from('notification_preferences')
      .upsert({
        user_id: userId,
        notification_type: 'email_digest',
        delivery_method: 'email',
        is_enabled: true,
        updated_at: new Date().toISOString()
      });
  }

  private async disableEmailNotifications(userId: string): Promise<void> {
    await this.supabase
      .from('notification_preferences')
      .update({
        is_enabled: false,
        updated_at: new Date().toISOString()
      })
      .eq('user_id', userId)
      .eq('delivery_method', 'email');
  }

  private async recordDataProcessing(
    userId: string,
    processing: Omit<DataProcessingRecord, 'userId' | 'createdAt' | 'updatedAt'>
  ): Promise<void> {
    await this.supabase
      .from('data_processing_records')
      .insert({
        user_id: userId,
        processing_type: processing.processingType,
        legal_basis: processing.legalBasis,
        purpose: processing.purpose,
        data_categories: processing.dataCategories,
        retention_period: processing.retentionPeriod,
        third_party_sharing: processing.thirdPartySharing,
        third_parties: processing.thirdParties,
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
      });
  }

  private async checkRateLimits(userId: string): Promise<{
    withinLimits: boolean;
    reason?: string;
  }> {
    const now = new Date();
    const windowStart = new Date(now.getTime() - (this.settings.deliverySettings.rateLimitWindow * 60 * 1000));

    const { data: recentEmails } = await this.supabase
      .from('email_delivery_logs')
      .select('delivery_timestamp')
      .eq('user_id', userId)
      .gte('delivery_timestamp', windowStart.toISOString());

    const emailCount = recentEmails?.length || 0;

    if (emailCount >= this.settings.deliverySettings.rateLimitMax) {
      return {
        withinLimits: false,
        reason: `${emailCount} emails sent in last ${this.settings.deliverySettings.rateLimitWindow} minutes`
      };
    }

    return { withinLimits: true };
  }

  private async checkSenderReputation(userId: string): Promise<{
    acceptable: boolean;
    reason?: string;
  }> {
    // Check recent bounce and complaint rates for this user
    const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);

    const { data: recentDeliveries } = await this.supabase
      .from('email_delivery_logs')
      .select('delivery_status, bounce_reason')
      .eq('user_id', userId)
      .gte('delivery_timestamp', sevenDaysAgo.toISOString());

    if (!recentDeliveries || recentDeliveries.length === 0) {
      return { acceptable: true };
    }

    const totalEmails = recentDeliveries.length;
    const bounces = recentDeliveries.filter(d => d.delivery_status === 'bounced').length;
    const complaints = recentDeliveries.filter(d => 
      d.delivery_status === 'spam' || 
      d.bounce_reason?.toLowerCase().includes('spam')
    ).length;

    const bounceRate = (bounces / totalEmails) * 100;
    const complaintRate = (complaints / totalEmails) * 100;

    if (bounceRate > this.settings.deliverySettings.bounceThreshold) {
      return {
        acceptable: false,
        reason: `High bounce rate: ${bounceRate.toFixed(2)}%`
      };
    }

    if (complaintRate > this.settings.deliverySettings.spamComplaintThreshold) {
      return {
        acceptable: false,
        reason: `High complaint rate: ${complaintRate.toFixed(2)}%`
      };
    }

    return { acceptable: true };
  }

  private generateCanSpamFooter(unsubscribeUrl: string): string {
    const address = this.settings.canSpam.senderAddress;
    
    return `
<div style="background: #f8f9fa; padding: 20px; margin-top: 40px; border-top: 1px solid #dee2e6; font-size: 12px; color: #6c757d; font-family: Arial, sans-serif;">
  <div style="max-width: 600px; margin: 0 auto;">
    <p style="margin-bottom: 10px;"><strong>You received this email because you subscribed to ArXiv Research Hub.</strong></p>
    
    <p style="margin-bottom: 15px;">
      ${this.settings.canSpam.senderName}<br>
      ${address.street}<br>
      ${address.city}, ${address.state} ${address.zipCode}<br>
      ${address.country}
    </p>
    
    <p style="margin-bottom: 10px;">
      <a href="${unsubscribeUrl}" style="color: #007bff; text-decoration: underline;">
        Click here to unsubscribe
      </a> or reply to this email with "UNSUBSCRIBE" in the subject line.
    </p>
    
    <p style="font-size: 11px; color: #868e96;">
      This email complies with the U.S. CAN-SPAM Act of 2003. 
      You can unsubscribe at any time and we will process your request within 10 business days.
    </p>
  </div>
</div>`;
  }

  private generateGDPRNotice(): string {
    return `
<div style="background: #e3f2fd; padding: 15px; margin-top: 20px; border-left: 4px solid #2196f3; font-size: 12px; color: #424242; font-family: Arial, sans-serif;">
  <p style="margin-bottom: 8px;"><strong>Privacy Notice (GDPR)</strong></p>
  <p style="margin-bottom: 8px;">
    We process your personal data based on your consent to provide personalized research recommendations. 
    You have the right to access, rectify, erase, or port your data.
  </p>
  <p>
    <a href="${this.settings.gdpr.privacyPolicyUrl}" style="color: #1976d2;">Privacy Policy</a> | 
    Contact our DPO: ${this.settings.gdpr.dpoContact}
  </p>
</div>`;
  }

  private async processDataErasure(userId: string, requestId: string): Promise<void> {
    // This would implement the actual data deletion process
    // For now, we'll just mark the request as processed
    await this.supabase
      .from('gdpr_requests')
      .update({
        request_status: 'in_progress',
        processed_at: new Date().toISOString()
      })
      .eq('request_id', requestId);

    this.logger.info(`Data erasure initiated for user ${userId} (request: ${requestId})`);
  }

  private async generateDataExport(userId: string, requestId: string): Promise<void> {
    // This would implement the actual data export process
    // For now, we'll just mark the request as processed
    await this.supabase
      .from('gdpr_requests')
      .update({
        request_status: 'in_progress',
        processed_at: new Date().toISOString()
      })
      .eq('request_id', requestId);

    this.logger.info(`Data export initiated for user ${userId} (request: ${requestId})`);
  }
}